package com.traffic.controller;


import cn.hutool.core.util.StrUtil;
import cn.jpush.api.push.PushResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.traffic.annotation.ApiJsonObject;
import com.traffic.annotation.ApiJsonProperty;
import com.traffic.constant.Status;
import com.traffic.entity.Message;
import com.traffic.entity.OldMessage;
import com.traffic.entity.User;
import com.traffic.model.ApiResponse;
import com.traffic.service.OldMessageService;
import com.traffic.service.PushService;
import com.traffic.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags = "消息推送相关接口")
@RestController
@RequestMapping(value = "/push")
@Slf4j
public class PushController {

    @Autowired
    private PushService pushService;

    @Autowired
    private UserService userService;

    @Autowired
    private OldMessageService oldMessageService;

    @ApiOperation(value = "【推送消息】后台管理员获取列表", notes = "推送消息列表")
    //@ApiImplicitParam(paramType = "path", dataType = "String", name = "accessToken", value = "一键登录三方SDK返回的验证字符串", required = true)
    @GetMapping("/getlist/{page}")
    public ApiResponse MessageList(@PathVariable Integer page) {

        Integer count = pushService.count();

        IPage<Message> MIPage = new Page<Message>(page, 10,count);
        IPage<Message> messages = pushService.page(MIPage);

//        QueryWrapper<Message> wrapper = new QueryWrapper<>();
//        List<Message> messages = pushService.list(wrapper.orderByDesc("createtime"));

        return ApiResponse.ofStatus(Status.OK,messages);

    }

    @ApiOperation(value = "【推送消息】后台管理员筛选", notes = "关键词模糊查询标题")
    @PostMapping("/search")
    @ApiJsonObject(name = "param",value = {
            @ApiJsonProperty(type =String.class,key = "content",example = "通知xxxxxxx" , description = "筛选内容"),
            @ApiJsonProperty(type =String.class,key = "starttime",example = "2020-10-28 12:00:00" , description = "筛选开始时间"),
            @ApiJsonProperty(type =String.class,key = "endtime",example = "2020-10-28 12:00:00" , description = "筛选结束时间")

    })
    public ApiResponse searchMessage(@RequestBody Map<String, String> param) throws ParseException {

        String content = ""+param.get("content");
        String starttime = ""+param.get("starttime");
        String endtime = ""+param.get("endtime");

        List<Message> messages =  pushService.searchList(starttime,endtime,content);
        if (messages.isEmpty()) {
            return ApiResponse.ofStatus(Status.OK);
        }else {
            return ApiResponse.ofStatus(Status.OK, messages);
        }
    }



    @ApiOperation(value = "【推送消息】", notes = "推所有人")
    @PostMapping("/pushmessage")
    @ApiJsonObject(name = "param",value = {
            @ApiJsonProperty(type =String.class,key = "title",example = "标题" , description = "标题"),
            @ApiJsonProperty(type =String.class,key = "content",example = "通知xxxxxxx" , description = "筛选内容"),
            @ApiJsonProperty(type =String.class,key = "acceptuser",example = "1,5,13,29," , description = "接收用户，传id，用,隔开"),
            @ApiJsonProperty(type =String.class,key = "all",example = "0/1" , description = "是否广播所有用户,0否1是"),

    })
    public ApiResponse newMessage(@RequestBody Map<String, String> param){

        String content = ""+param.get("content");
        String title = ""+param.get("title");
        String acceptuser = ""+param.get("acceptuser");
        Integer all = Integer.parseInt(param.get("all"));
        String user="";
        List<String> users = new ArrayList<>();
        if(all == 1){
            user="所有用户";
        }else{
            users = Stream.of(acceptuser.split(",")).collect(Collectors.toList());
            user = acceptuser;
        }

        Message me = Message.builder().acceptuser(user).title(title).content(content).type(0).createtime(new Date()).build();

        pushService.save(me);

        if(all ==0){

            PushResult reult=pushService.testSendPush(users,content,title);

        }else {
            PushResult reult=pushService.testSendPush(content,title);
        }

        return ApiResponse.ofStatus(Status.OK);

    }


    @ApiOperation(value = "【推送消息】获取用户个人消息", notes = "推送消息列表")
    //@ApiImplicitParam(paramType = "path", dataType = "String", name = "accessToken", value = "一键登录三方SDK返回的验证字符串", required = true)
    @GetMapping("/usermessage/{userid}")
    public ApiResponse UserMessageList(@PathVariable Long userid) {

        List<Message> messages = pushService.list();
        User user = userService.getById(userid);
        List<Message> retmessage = new ArrayList<>();
        for (Message m: messages) {

            String accepters = m.getAcceptuser();
            if(accepters.contains(user.getRegistrationid()))retmessage.add(m);
            if(accepters.contains("所有用户"))retmessage.add(m);

        }

//        QueryWrapper<Message> wrapper = new QueryWrapper<>();
//        List<Message> messages = pushService.list(wrapper.orderByDesc("createtime"));

        return ApiResponse.ofStatus(Status.OK,retmessage);

    }


    @ApiOperation(value = "【获取消息】获取用户已读消息", notes = "已读最新消息id")
    //@ApiImplicitParam(paramType = "path", dataType = "String", name = "accessToken", value = "一键登录三方SDK返回的验证字符串", required = true)
    @GetMapping("/getoldmessage/{userid}/{type}")
    public ApiResponse OldMessageList(@PathVariable Long userid,@PathVariable Integer type) {

        QueryWrapper<OldMessage> wrapper = new QueryWrapper<>();
        OldMessage oldMessage = oldMessageService.getOne(wrapper.eq("user_id",userid).eq("type",type));

        if(ObjectUtils.isEmpty(oldMessage)){
            oldMessage = OldMessage.builder().messageId(new Long(0)).userId(userid).type(type).build();
            oldMessageService.save(oldMessage);
            return ApiResponse.ofStatus(Status.OK,oldMessage.getMessageId());
        }


        return ApiResponse.ofStatus(Status.OK,oldMessage.getMessageId());
    }

    @ApiOperation(value = "【删除消息】标记用户已读", notes = "设置已读最新消息id")
    //@ApiImplicitParam(paramType = "path", dataType = "String", name = "accessToken", value = "一键登录三方SDK返回的验证字符串", required = true)
    @GetMapping("/setoldmessage/{userid}/{messageid}/{type}")
    public ApiResponse OldMessageList(@PathVariable Long userid,@PathVariable Long messageid,@PathVariable Integer type) {

        QueryWrapper<OldMessage> qwrapper = new QueryWrapper<>();
        OldMessage oldMessage = oldMessageService.getOne(qwrapper.eq("user_id",userid).eq("type",type));

        if(ObjectUtils.isEmpty(oldMessage)){
            oldMessageService.save(OldMessage.builder().messageId(messageid).userId(userid).type(type).build());
            return ApiResponse.ofStatus(Status.OK,"已设置已读信息id");
        }

        UpdateWrapper<OldMessage> uwrapper = new UpdateWrapper<>();
        oldMessageService.update(uwrapper.eq("user_id",userid).eq("type",type).set("message_id",messageid));

        return ApiResponse.ofStatus(Status.OK,"已设置已读信息id");
    }

}
